﻿using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;

namespace TiaoTiaoCode.Common.Helpers
{
    public class TiaoTiaoIP
    {
        /// <summary>
        /// 根据适配器名获取IP
        /// </summary>
        /// <param name="adapterName"></param>
        /// <returns></returns>
        public static string GetCardIP(string adapterName)
        {
            var ips = new List<string>();
            var nis = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var n in nis)
            {
                if (n.Name != adapterName) continue;
                var uAddr = n.GetIPProperties().UnicastAddresses;
                var tmpIps = uAddr.Where(t => t.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
                ips.AddRange(tmpIps.Select(t => t.Address.ToString()));
            }

            return ips.FirstOrDefault();
        }

        /// <summary>
        /// 单网卡获取IP用这个
        /// </summary>
        /// <returns></returns>
        public string? GetIP()
        {
            var addrs = Dns.GetHostAddresses(Dns.GetHostName());
            var ips = addrs.Where(t => t.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

            return ips.FirstOrDefault()?.ToString();
        }
    }
}
